import re,random
from datetime import datetime

from flask import Blueprint, jsonify, current_app, request
from flask_restful import Api,Resource,reqparse
from models.model import *
from utils.JwtTools import JwtTool
from utils.QiniuTools import QiniuTool
from utils.RedisTools import RedisTool
from utils.SmsTools import SmsTool

user_bp = Blueprint("user_bp",__name__,url_prefix="/user")

api = Api(user_bp)

# 异步发送验证码
def send_msg(mobile,code):
    from app import app
    with app.app_context():   #手动开启上下文
        s = SmsTool().send(mobile,code)
        if s:
            print("发送成功")
        else:
            print("发送失败")
# 发送验证的视图
class SmsView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument("mobile",required=True)
        args = req.parse_args()
        rs = r'^1[3-9]\d{9}$'
        res = re.match(rs,args["mobile"])
        if not res:
            return jsonify({
                "code": 400,
                "msg": "手机号格式错误"
            })
        code = random.randint(100000,999999)
        time = current_app.config.get("TIME")
        RedisTool().rds.set("sms_%s"%args["mobile"],code,ex=time*60)
        current_app.schedul.add_job(send_msg,args=(args['mobile'],code))
        return jsonify({
            "code": 200,
            "msg": "发送成功"
        })

# 登陆注册视图
class LoginView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument("mobile",required=True)
        req.add_argument("code")
        args = req.parse_args()
        rs = r'^1[3-9]\d{9}$'
        res = re.match(rs, args["mobile"])
        if not res:
            return jsonify({
                "code": 400,
                "msg": "手机号格式错误"
            })
        code = RedisTool().rds.get("sms_%s"%args["mobile"])
        if not code:
            return jsonify({
                "code": 400,
                "msg": "验证码过期"
            })
        if args["code"] != code.decode():
            return jsonify({
                "code": 400,
                "msg": "验证码错误"
            })
        user_info = UserModel.query.filter(UserModel.mobile == args["mobile"]).first()
        username = '游客' + args["mobile"][-4:]
        if not user_info:
            u = UserModel(
                mobile = args["mobile"],
                username = username
            )
            db.session.add(u)
            db.session.commit()
        user_info = UserModel.query.filter(UserModel.mobile == args["mobile"]).first()
        payload = {
            "uid": user_info.uid,
            "username": user_info.username
        }
        token = JwtTool().create(payload)

        return jsonify({
            "code": 200,
            "msg": "登录成功",
            "token": token
        })

class UploadImg(Resource):
    def post(self):
        img = request.files.get("file")
        d = datetime.strftime(datetime.now(),"%Y%m%d%H%M%S")
        t = str(random.randint(100000,999999))
        filename = d + t + '.png'
        save_path = 'static/image/%s'%filename
        img.save(save_path)
        q = QiniuTool().uploadImg(save_path,save_path)
        if not q:
            return jsonify({
                "code": 400,
                "msg": "文件上传失败"
            })
        return jsonify({
            "code": 200,
            "msg": "文件上传成功",
            "key": q
        })

class UploadAudio(Resource):
    def post(self):
        img = request.files.get("file")
        d = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S")
        t = str(random.randint(100000, 999999))
        filename = d + t + '.mp3'
        save_path = 'static/audio/%s' % filename
        img.save(save_path)
        q = QiniuTool().uploadImg(save_path, save_path)
        if not q:
            return jsonify({
                "code": 400,
                "msg": "文件上传失败"
            })
        return jsonify({
            "code": 200,
            "msg": "文件上传成功",
            "key": q
        })


api.add_resource(SmsView,"/sms")
api.add_resource(LoginView,"/login")
api.add_resource(UploadImg,"/img")
api.add_resource(UploadAudio,"/audio")